package com.atguigu.srb.core.interceptor;

import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.entity.UserInfo;
import com.atguigu.srb.core.service.UserInfoService;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferStrategy;

/**
 * @Description:
 * @Author: Gavin
 * @Date: 7/15/2023 9:52 AM
 */
// @Component
    //可以不使用@Component这种方式
public class UserStatusInterceptor implements HandlerInterceptor {
    // @Resource
    //使用这种方式来获得userInfoService
    UserInfoService userInfoService;
    public UserStatusInterceptor(UserInfoService userInfoService){
        this.userInfoService = userInfoService;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户的访问的路径
        String path = request.getRequestURI();
        //进行路径的比较
        AntPathMatcher matcher = new AntPathMatcher();
        if (!matcher.match("/**/auth/**",path)) {
            //进来这里面说明,不是我们要拦截的url,直接放行
            return true;
        }
        //继续往下走,需要判断用户的状态是锁定还是非锁定的
        //获取用户的token
        String token = request.getHeader("token");
        //根据token查询用户的信息
        UserInfo userInfo = userInfoService.getById(JwtUtils.getUserId(token));
        //判断用户的status
        if(userInfo.getStatus() == 1){
            //进来这里面说明用户的状态是正常的,直接放行
            return true;
        }
        //能走到这里,说明不匹配,账户被锁定
        throw new BusinessException(ResponseEnum.LOGIN_LOCKED_ERROR);
    }
}
